<template>
  <el-card>
    <el-form
      label-width="120px"
      size="small"
      :model="formData"
      :rules="rules"
      ref="ruleForm"
    >
      <el-form-item label="SPU名称"> {{ toAddSkuData.spuName }} </el-form-item>
      <el-form-item label="SKU名称" prop="skuName">
        <el-input v-model="formData.skuName"></el-input>
      </el-form-item>
      <el-form-item label="价格（元）" prop="price">
        <el-input v-model="formData.price"></el-input>
      </el-form-item>
      <el-form-item label="重量（千克）" prop="weight">
        <el-input v-model="formData.weight"></el-input>
      </el-form-item>
      <el-form-item label="规格描述" prop="skuDesc">
        <el-input v-model="formData.skuDesc"></el-input>
      </el-form-item>
      <el-form-item label="平台属性" prop="skuAttrValueList">
        <div class="wrap-wrap">
          <div
            class="selector-wrap"
            v-for="(attr, index) in receive.skuAttrValueList"
            :key="attr.id"
          >
            <span>{{ attr.attrName }}: </span>
            <el-select
              placeholder="请选择"
              v-model="formData.skuAttrValueList[index]"
            >
              <el-option
                :value="`${attr.id}-${attr.attrName}-${value.id}-${value.valueName}`"
                :label="value.valueName"
                v-for="value in attr.attrValueList"
                :key="value.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <div class="wrap-wrap">
          <div
            class="selector-wrap"
            v-for="(saleAttr, index) in receive.skuSaleAttrValueList"
            :key="saleAttr.id"
          >
            <span>{{ saleAttr.saleAttrName }}: </span>
            <el-select
              placeholder="请选择"
              v-model="formData.skuSaleAttrValueList[index]"
            >
              <el-option
                :value="`${saleAttrValue.baseSaleAttrId}-${saleAttrValue.saleAttrName}-${saleAttrValue.id}-${saleAttrValue.saleAttrValueName}`"
                :label="saleAttrValue.saleAttrValueName"
                v-for="saleAttrValue in saleAttr.spuSaleAttrValueList"
                :key="saleAttrValue.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="receive.skuImageList"
          border
          @selection-change="handleSelectionChange"
          ref="imgTableRef"
        >
          <el-table-column type="selection" width="55" align="center">
          </el-table-column>
          <el-table-column label="图片">
            <template #default="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"> </el-table-column>
          <el-table-column label="操作">
            <template #default="{ row }">
              <el-button
                v-if="row.isDefault === '0'"
                size="mini"
                type="primary"
                @click="setDefaultImg(row)"
              >
                设为默认
              </el-button>
              <el-tag type="success" size="mini" v-show="row.isDefault === '1'">
                默认
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="submitForm('ruleForm')">
          保存
        </el-button>
        <el-button size="mini" @click="$emit('changShowNum', 1)">
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { mapState } from 'vuex'
import { getAttrInfoListApi } from '@/api/product/attrApi'
import { category2IdApi, category1IdApi } from '@/api/product/getCategoryApi'
import {
  getSpuSaleAttrListApi,
  getSpuImageListApi,
  getSpuApi
} from '@/api/product/spuApi'
import { addSkuApi, updateSkuInfoApi } from '@/api/product/skuApi'
export default {
  name: 'AddSku',
  props: {
    toAddSkuData: {
      type: Object,
      default: () => ({}),
      required: true
    },
    skuInfo: {
      type: Object,
      default: () => null
    }
  },
  data() {
    const skuImageListValid = (rule, value, callback) => {
      if (!value.length) {
        callback(new Error('请选择至少一张图片作为sku图片'))
        return
      }
      if (value.every((item) => item.isDefault !== '1')) {
        callback(new Error('请从勾选的图片中设置一张sku默认图片'))
        return
      }
      callback()
    }
    return {
      receive: {
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
        skuImageList: []
      },
      // 收集表单数据
      formData: {
        skuName: '',
        weight: '',
        price: 0,
        skuDesc: '',
        skuDefaultImg: '',
        // spuId: '',
        skuAttrValueList: [],
        skuSaleAttrValueList: [],
        skuImageList: []
      },
      // 表单校验
      rules: {
        skuName: [
          { required: true, message: '请输入SKU名称', trigger: 'blur' }
        ],
        weight: [{ required: true, message: '请输入SKU重量', trigger: 'blur' }],
        price: [{ required: true, message: '请输入SKU价格', trigger: 'blur' }],
        skuDesc: [
          { required: true, message: '请输入SKU描述', trigger: 'blur' }
        ],
        skuAttrValueList: [
          { required: true, message: '请选择至少一个平台属性' }
        ],
        skuSaleAttrValueList: [
          { required: true, message: '请选择至少一个销售属性' }
        ],
        skuImageList: [{ required: true, validator: skuImageListValid }]
      },
      category2Id: undefined,
      category1Id: undefined,
      checkIndex: [],
      defaultIndex: undefined
    }
  },
  computed: {
    ...mapState('category', ['category'])
  },
  mounted() {
    console.log(this.skuInfo)
    Promise.all([
      this.getAttrList(),
      // this.getSaleAttrList(),
      this.getSpuImageList(),
      this.getSpu()
    ])
    if (this.skuInfo) {
      this.formData.skuName = this.skuInfo.skuName
      this.formData.skuDesc = this.skuInfo.skuDesc
      this.formData.weight = this.skuInfo.weight
      this.formData.price = this.skuInfo.price
    }
  },
  methods: {
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          if (!this.skuInfo) {
            // 新增sku的请求
            await addSkuApi({
              ...this.formData,
              category3Id: this.category.category3Id,
              spuId: this.toAddSkuData.id,
              skuAttrValueList: this.formData.skuAttrValueList.map((attr) => {
                const [attrId, attrName, valueId, valueName] = attr.split('-')
                return { attrId, attrName, valueId, valueName }
              }),
              skuSaleAttrValueList: this.formData.skuSaleAttrValueList.map(
                (attr) => {
                  const [
                    saleAttrId,
                    saleAttrName,
                    saleAttrValueId,
                    saleAttrValueName
                  ] = attr.split('-')
                  return {
                    saleAttrId,
                    saleAttrName,
                    saleAttrValueId,
                    saleAttrValueName
                  }
                }
              ),
              skuImageList: this.formData.skuImageList.map((item) => {
                return { ...item, spuImgId: item.id }
              })
            })
            this.$message.success('添加成功')
          } else {
            // 修改sku
            await updateSkuInfoApi({
              ...this.skuInfo,
              ...this.formData,
              skuAttrValueList: this.skuInfo.skuAttrValueList,
              skuSaleAttrValueList: this.skuInfo.skuAttrValueList,
              tmId: 3741
              // skuId: this.skuInfo.id
            })
            this.$message.success('修改成功')
          }
          this.$emit('changShowNum', 1)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 选择框
    handleSelectionChange(val) {
      this.formData.skuImageList = val
    },
    // 设置默认图片
    setDefaultImg(data) {
      this.receive.skuImageList.forEach((item) => (item.isDefault = '0'))
      data.isDefault = '1'
      this.formData.skuDefaultImg = data.imgUrl
      this.$refs.ruleForm.validateField('skuImageList')
    },
    // 封装请求平台属性的方法
    async getAttrList() {
      if (
        !this.category.category1Id ||
        !this.category.category2Id ||
        !this.category.category3Id
      ) {
        this.category2Id = (
          await category2IdApi(this.skuInfo.category3Id)
        ).data.category2Id
        this.category1Id = (
          await category1IdApi(this.category2Id)
        ).data.category1Id
        const res = await getAttrInfoListApi(
          this.category1Id,
          this.category2Id,
          this.skuInfo.category3Id
        )
        this.receive.skuAttrValueList = res.data
        return
      }
      const res = await getAttrInfoListApi(
        this.category.category1Id,
        this.category.category2Id,
        this.category.category3Id
      )
      this.receive.skuAttrValueList = res.data
      // console.log(res.data)
    },
    // 封装请求销售属性的方法 ---- 好像用不上了
    async getSaleAttrList() {
      await getSpuSaleAttrListApi(this.toAddSkuData.id)
      // this.receive.skuSaleAttrValueList = res.data
      // console.log(res.data)
    },
    // 封装请求图片的方法
    async getSpuImageList() {
      const res = await getSpuImageListApi(this.toAddSkuData.id)
      this.receive.skuImageList = res.data.map((item) => {
        item.isDefault = '0'
        return item
      })

      if (!this.skuInfo) return
      this.skuInfo.skuImageList.forEach((img) => {
        const i = this.receive.skuImageList.findIndex((item, index) => {
          if (img.isDefault === '1' && img.spuImgId === item.id) {
            this.receive.skuImageList[index].isDefault = '1'
          }
          return img.imgUrl === item.imgUrl
        })
        this.$nextTick(() => {
          this.$refs.imgTableRef.toggleRowSelection(
            this.receive.skuImageList[i],
            true
          )
        })
      })
    },
    // 封装获取spu基本信息的方法
    async getSpu() {
      const res = await getSpuApi(this.toAddSkuData.id)
      this.receive.skuSaleAttrValueList = res.data.spuSaleAttrList
      this.toAddSkuData.spuName = res.data.spuName
      // console.log(res.data)
    }
  }
}
</script>

<style scoped>
.selector-wrap {
  display: inline-block;
  width: 350px;
  margin-bottom: 10px;
  font-weight: 700;
}
.selector-wrap span {
  display: inline-block;
  width: 120px;
  text-align: right;
  padding-right: 7px;
}
.wrap-wrap {
  padding: 0 20px;
}
.sku-img {
  height: 100px;
}
</style>
